package com.example.controller;

import com.example.common.ApiResult;
import com.example.entity.Student;
import com.example.service.StudentService;
import com.example.util.AuthUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 学生 RESTful API（前后端分离）
 */
@Tag(name = "学生管理", description = "学生信息的增删改查操作")
@RestController
@RequestMapping("/api/students") // 路由组
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Operation(summary = "获取学生列表", description = "获取所有学生信息列表", 
               security = @SecurityRequirement(name = "bearerAuth"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "0", description = "获取成功"),
            @ApiResponse(responseCode = "-1", description = "获取失败")
    })
    @GetMapping
    public ApiResult<List<Student>> list() {
        // 获取当前登录用户信息（由JWT过滤器设置）
        String currentUser = AuthUtils.getCurrentUsername();
        System.out.println("当前操作用户: " + currentUser + " - 正在查询学生列表");
        
        List<Student> students = studentService.list();
        return ApiResult.success("获取学生信息列表成功", students);
    }

    @Operation(summary = "根据ID获取学生", description = "根据学生ID获取单个学生详细信息", 
               security = @SecurityRequirement(name = "bearerAuth"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "0", description = "获取成功"),
            @ApiResponse(responseCode = "-1", description = "学生不存在")
    })
    @GetMapping("/{id}")
    public ApiResult<Student> get(
            @Parameter(description = "学生ID", required = true) 
            @PathVariable Long id) {
        Student student = studentService.getById(id);
        if (student == null) {
            return ApiResult.notFound();
        }
        return ApiResult.success("获取学生信息成功", student);
    }

    @Operation(summary = "创建学生", description = "创建新的学生信息", 
               security = @SecurityRequirement(name = "bearerAuth"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "0", description = "创建成功"),
            @ApiResponse(responseCode = "-1", description = "创建失败")
    })
    @PostMapping
    public ApiResult<Student> create(
            @Parameter(description = "学生信息", required = true) 
            @RequestBody Student student) {
        boolean success = studentService.save(student);
        if (!success) {
            return ApiResult.error("创建学生失败");
        }
        return ApiResult.success("创建学生成功", student);
    }

    @Operation(summary = "更新学生信息", description = "根据ID更新学生信息（部分或全部字段）", 
               security = @SecurityRequirement(name = "bearerAuth"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "0", description = "更新成功"),
            @ApiResponse(responseCode = "-1", description = "更新失败，学生不存在")
    })
    @PutMapping("/{id}")
    public ApiResult<Student> update(
            @Parameter(description = "学生ID", required = true) 
            @PathVariable Long id, 
            @Parameter(description = "更新的学生信息", required = true) 
            @RequestBody Student student) {
        student.setId(id);
        boolean success = studentService.updateById(student);
        if (!success) {
            return ApiResult.error("更新学生失败，学生不存在");
        }
        return ApiResult.success("更新学生成功", student);
    }

    @Operation(summary = "删除学生", description = "根据ID删除学生信息", 
               security = @SecurityRequirement(name = "bearerAuth"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "0", description = "删除成功"),
            @ApiResponse(responseCode = "-1", description = "删除失败，学生不存在")
    })
    @DeleteMapping("/{id}")
    public ApiResult<String> delete(
            @Parameter(description = "学生ID", required = true) 
            @PathVariable Long id) {
        boolean success = studentService.removeById(id);
        if (!success) {
            return ApiResult.error("删除学生失败，学生不存在");
        }
        return ApiResult.success("删除学生成功", "删除成功");
    }

    @Operation(summary = "按姓名搜索学生", description = "根据姓名关键字搜索学生信息", 
               security = @SecurityRequirement(name = "bearerAuth"))
    @ApiResponses(value = {
            @ApiResponse(responseCode = "0", description = "搜索完成"),
            @ApiResponse(responseCode = "-1", description = "搜索失败")
    })
    @GetMapping("/search")
    public ApiResult<List<Student>> searchByName(
            @Parameter(description = "姓名关键字", required = true, example = "张") 
            @RequestParam String name) {
        List<Student> allStudents = studentService.list();
        
        // 使用 getFullName() 方法进行姓名匹配
        List<Student> matchedStudents = allStudents.stream()
                .filter(student -> student.getFullName() != null && 
                                 student.getFullName().contains(name))
                .collect(java.util.stream.Collectors.toList());
        
        return ApiResult.success("搜索完成", matchedStudents);
    }
}
